//
//  CAHomeController.m
//  cascade-realm
//
//  Created by QSC on 20/5/24.
//

#import "CAHomeController.h"
#import "CAHomeCollectionCell.h"
#import "CADataModel.h"
#import "CADetailController.h"
@interface CAHomeController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic,strong)UICollectionView * collectionView;
@property(nonatomic,strong)UIView * line;
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,strong)NSMutableArray * blockIds;
@property(nonatomic,assign)CGFloat  CellH;
@end

@implementation CAHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navView.hidden = YES;
    
    [self setUpView];
    
    [self getDatas];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDatas) name:BlockDidChange object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(followChange) name:FollowDidChange object:nil];
}

- (void)setUpView{
    
    UIImageView *bgImgv = [[UIImageView alloc] initWithImage:Img(@"bg_home")];
    [self.view addSubview:bgImgv];
    bgImgv.contentMode = UIViewContentModeScaleAspectFit;

    [bgImgv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        if (IsX){
          
        }else{
            make.height.mas_equalTo(ScreenW * 0.7);
        }
       
        make.top.equalTo(self.view).offset(kNavigationBarHeight);
        
    }];
    
    UIImageView *titleImgv = [[UIImageView alloc] initWithImage:Img(@"title_home")];
    [self.view addSubview:titleImgv];
    [titleImgv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(bgImgv.mas_top).offset(10);
    }];
    
   
    UIView * line = [UIView new];
    [self.view addSubview:line];
    line.clipsToBounds = true;
    
    UILabel * titleLabel = [UILabel LabelWithFont:BoldFont(16) color:Hex(0x404040) text:@"Explore"];
    [self.view addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.equalTo(bgImgv.mas_bottom).offset(15);
    }];
    
    UIImageView *iconImgv = [[UIImageView alloc] initWithImage:Img(@"icon_home")];
    [self.view addSubview:iconImgv];
    [iconImgv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(titleLabel);
        make.left.equalTo(titleLabel.mas_right);
    }];
    
    
    line.layer.cornerRadius = 5;
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(titleLabel).offset(2);
        make.left.equalTo(titleLabel).offset(6);
        make.right.equalTo(titleLabel);
        make.height.mas_equalTo(10);
    }];
    self.line = line;
   
    
    [self.view addSubview:self.collectionView];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(titleLabel.mas_bottom).offset(0);
        make.bottom.equalTo(self.view).offset(-kTabBarHeight);
    }];

}

- (void)followChange{
    [self.collectionView reloadData];
}


- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.collectionView reloadData];
    
   
    
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if(self.CellH == 0){
        self.CellH = self.collectionView.height - 20;
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        CGFloat itmeH = self.CellH;
        layout.itemSize = CGSizeMake(itmeH * 8/9 , itmeH);
        
        layout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20);
        layout.minimumInteritemSpacing = 15;
 
        //水平滚动
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        [self.collectionView setCollectionViewLayout:layout];
    }
    [Tool colorGradientLayerForView:self.line frame:self.line.bounds colors:@[Hex(0xCEF568),[Hex(0xCEF568) colorWithAlphaComponent:0.0]] locations:@[@0.1, @1.0]];
}

- (UICollectionView *)collectionView{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        CGFloat itmeH = 200;
        layout.itemSize = CGSizeMake(itmeH * 8/9 , itmeH);
        
        layout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20);
        layout.minimumInteritemSpacing = 15;
 
        //水平滚动
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
        
        collectionView.backgroundColor = [UIColor whiteColor];
        collectionView.dataSource = self;
        collectionView.delegate = self;
        
        [collectionView registerClass:[CAHomeCollectionCell class] forCellWithReuseIdentifier:@"CAHomeCollectionCell"];
        // 去掉滚动条
        collectionView.showsHorizontalScrollIndicator = NO;
     
        collectionView.bounces = NO;
        _collectionView = collectionView;
    }
    return  _collectionView;;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.dataArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *) collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    CAHomeCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CAHomeCollectionCell" forIndexPath:indexPath];
    
    cell.model = self.dataArray[indexPath.row];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    CADataModel * model = self.dataArray[indexPath.row];
    CADetailController * vc = [CADetailController new];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)getDatas{
    
    WeakSelf
  
    [CADataModel getHomeDataModels:^(NSArray * _Nonnull array) {
        weakSelf.dataArray = [NSMutableArray arrayWithArray:array];
        
        [weakSelf.collectionView reloadData];
        [weakSelf reloadBlockUser];
   
    }];
}


- (void)reloadBlockUser{
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_group_enter(group);
    
    [Http postWithURL:getblockList params:@{} isShowHud:NO isLogin:NO success:^(id  _Nonnull responseObject) {
        
        NSArray * array = [CAHomeUser mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        self.blockIds = [NSMutableArray array];
        for (CAHomeUser * user in array) {
            [self.blockIds addObject:user.broadcasterId];
        }
        
        NSMutableArray * newDataArray = [NSMutableArray array];
        if (self.blockIds.count > 0) {
            for (CADataModel * model in self.dataArray) {
                if (![self.blockIds containsObject:model.binduserId]) {
                    [newDataArray addObject:model];
                }
            }
            self.dataArray = newDataArray;
          
   
        }
        dispatch_group_leave(group);
    } failure:^(id  _Nonnull errObject) {
        dispatch_group_leave(group);
    }];
    
    NSDictionary * dic = @{@"limit":@"100",@"page":@"1"};
    
    [Http postWithURL:getFriendsListPage params:dic isShowHud:NO isLogin:NO success:^(id  _Nonnull responseObject) {
        
        NSArray * array = [CAHomeUser mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        NSMutableArray * followIds = [NSMutableArray array];
        
        for (CAHomeUser * user in array) {
            [followIds addObject:user.userId];
        }
        CAUserInfo.shared.followIds = followIds;
        
        dispatch_group_leave(group);
       
            
    } failure:^(id  _Nonnull errObject) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        //界面刷新
        [self.collectionView reloadData];
    });

}

@end
